package com.liuwei.spring.cloud.junit.leetcode;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-interview-150
 */
@Slf4j
public class ThreeSum {

    public static void main(String[] args) {
        ThreeSum instance = new ThreeSum();
        int[] nums = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> result = instance.threeSum(nums);
        log.info("{}", JSON.toJSONString(result));
    }

    public List<List<Integer>> threeSum(int[] nums) {
        return plus(0,nums,3);
//        return plus(-1,nums,1);
    }

    private List<List<Integer>>  plus(Integer total,int[] nums,int level) {
        List<List<Integer>> all = new ArrayList<>();
        for(int i=0;i<nums.length;i++){
            Integer value = nums[i];
            Integer left = total-value;
            if(level==1){
                if(total.equals(value)){
                    // 常常使用Arrays.asList()后调用add，remove这些method时出现java.lang.UnsupportedOperationException异常
                    List<Integer> list = new ArrayList<>();
                    list.add(value);
                    all.add(list);
                    return all;
                }
            }else{
                int[] others = ArrayUtils.remove(nums,i);
                List<List<Integer>> result = plus(left,others,level-1);
                if(CollectionUtils.isNotEmpty(result)){
                    for (int j = 0; j < result.size(); j++) {
                        List<Integer> item = result.get(j);
                        item.add(value);
                    }
                    all.addAll(result);
                }
            }
        }
        return all;
    }

    private int[] getLeftArray(int[] nums,int excludeIndex){
        return ArrayUtils.remove(nums,excludeIndex);
    }
}
